<template>
  <div
    class="table-page"
    :class="{ 'drag-over': isDragOver }"
    @drop="handleFileDrop"
    @dragover="handleDragOver"
    @dragenter="handleDragEnter"
    @dragleave="handleDragLeave"
  >
    <!-- 拖拽提示 -->
    <div v-if="isDragOver" class="drag-hint">
      <el-icon size="48"><Upload /></el-icon>
      <p>释放文件以直接添加记录</p>
    </div>
    <vxe-grid
      ref="gridTable"
      round
      show-header-overflow
      show-overflow
      :data="displayedData"
      :row-style="tableRowStyle"
      :border="border"
      :auto-resize="true"
      :loading="tableLoading"
      :size="size === 'default' ? 'small' : size === 'small' ? 'mini' : size === 'large' ? 'medium' : ''"
      :height="height"
      :columns="tableColumns"
      :scroll-y="{ enabled: true, gt: 0 }"
      :checkbox-config="{ checkField: 'checkbox', highlight: true, range: true, trigger: 'default' }"
      :column-config="{ resizable: true, useKey: true }"
      :row-config="{ isCurrent: true, keyField: 'Record_ID', useKey: true, isHover: true }"
      :menu-config="tableMenu"
      :toolbar-config="toolbarConfig"
      :print-config="{}"
      :import-config="{}"
      :export-config="{}"
      @menu-click="rightMenuClick"
      @cell-click="cellClick"
      @cell-dblclick="cellDblclick"
      @checkbox-change="checkboxChange"
      @checkbox-all="checkboxAll"
      @checkbox-range-end="checkboxRangeEnd"
      @keydown="handleKeydown"
    >
      <template #toolbarButtons>
        <slot name="toolbarButtons"></slot>
      </template>
      <!-- 自定义操作列标题模板 -->
      <template #FourAspect_Pass_default="{ row }">
        <div>
          {{ !row.FourAspect_Pass ? "未检测" : row.FourAspect_Pass == 2 ? "通过" : "未通过" }}
        </div>
      </template>
      <template #operation_title="{ column }">
        <div class="optionsColumn">
          <span>{{ column.title.text }}</span>
          <span v-if="column.title.count !== undefined">&nbsp;总数:{{ column.title.count }}</span>
          <span v-if="column.title.count !== undefined && gridTable.getCheckboxRecords().length > 0"
            >&nbsp;已选:{{ dynamicStore.tableSelect.length }}</span
          >
          <el-button v-if="columnType == 'folder'" :icon="searchSetting ? 'View' : 'Hide'" circle @click="emit('trigger')" />
        </div>
      </template>
      <!-- Status字段 -->
      <template #Status_default="{ row }">
        <span v-if="!dynamicClass[row.Status]"> 状态错误 </span>
        <el-tooltip effect="dark" :content="row.MarkContent" placement="top" v-else-if="row.MarkContent">
          <span :class="['circle', dynamicClass[row.Status]['class']]">{{ dynamicClass[row.Status]["name"] }}</span>
        </el-tooltip>
        <span v-else :class="['circle', dynamicClass[row.Status]['class']]">{{ dynamicClass[row.Status]["name"] }}</span>
      </template>
      <!-- IsLock字段 -->
      <template #IsLock_default="{ row }">
        <el-icon v-if="Number(row.IsLock)"><Lock /></el-icon>
        <el-icon v-else><Unlock /></el-icon>
      </template>
      <!-- lables字段 -->
      <template #lables_default="{ row }">
        <div v-if="row.lables">
          <el-tag
            v-for="(label, index) in labelFormatter({ row, column: { property: 'lables' }, cellValue: row.lables })"
            :key="index"
            type="info"
            size="small"
            style="margin-right: 4px; margin-bottom: 2px"
          >
            {{ label }}
          </el-tag>
        </div>
      </template>
      <template #Labels_default="{ row }">
        <div v-if="row.Labels">
          <el-tag
            v-for="(label, index) in labelFormatter({ row, column: { property: 'Labels' }, cellValue: row.Labels })"
            :key="index"
            type="info"
            size="small"
            style="margin-right: 4px; margin-bottom: 2px"
          >
            {{ label }}
          </el-tag>
        </div>
      </template>
      <template #labels_default="{ row }">
        <div v-if="row.labels">
          <el-tag
            v-for="(label, index) in labelFormatter({ row, column: { property: 'labels' }, cellValue: row.labels })"
            :key="index"
            type="info"
            size="small"
            style="margin-right: 4px; margin-bottom: 2px"
          >
            {{ label }}
          </el-tag>
        </div>
      </template>
      <template #operation="{ row }">
        <div class="columOptions">
          <a-dropdown v-if="props.childData.length > 0">
            <el-button icon="FolderOpened" link type="primary"> 卷内 </el-button>
            <template #overlay>
              <a-menu>
                <a-menu-item v-for="(item, index) in childData" :key="index">
                  <el-button link type="primary" @click="toSublevel(row, item)">
                    {{ item.FMT_Name }}
                  </el-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <el-button icon="View" link type="primary" @click="viewFullText(row)"> 全文 </el-button>
          <el-button
            icon="Coin"
            v-if="(fmtData as any[]).filter((v:any)=>v.FMT_ID === row.FMT_ID )[0]?.FMT_ShowMetaData"
            link
            type="primary"
            @click="showMetaData(row)"
          >
            元数据
          </el-button>
          <el-button icon="Document" link type="primary" @click="viewFourAspect(row)"> 四性 </el-button>
        </div>
      </template>
    </vxe-grid>
    <div class="loadImg" v-if="paginationShow && hasTableData">
      <el-tooltip class="item" effect="dark" content="下一页" placement="left">
        <img @click="pageNext" style="width: 30px; height: 30px; margin-bottom: 5px; margin-left: 2px" :src="nextImgUrl" alt="" />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="全部数据" placement="left">
        <img @click="pageAll" style="width: 35px" :src="allImgUrl" alt="" />
      </el-tooltip>
    </div>
    <!-- 弹窗组件 -->
    <el-dialog width="300" v-model="dialogVisible" title="模糊查找" @close="closeSearchDialog" :modal="false" :draggable="true">
      <el-input v-model="searchContent" placeholder="输入关键词进行查找"></el-input>
      <template #footer>
        <el-button type="primary" @click="searchTable">查找</el-button>
        <el-button @click="searchNext">查找下一个</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, watch, computed, onUnmounted, nextTick, PropType, onMounted } from "vue";
import { Upload } from "@element-plus/icons-vue";
import { VxeGridInstance, VxeUI } from "vxe-table";
import { useGlobalStore } from "@/stores/modules/global";
import { customFields } from "../dataType";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useCatalogStore } from "@/stores/modules/catalog";
import { useUserStore } from "@/stores/modules/user";
import { columnCoverter } from "@/views/system/dynamicMain/ts/until";
import { useRoute } from "vue-router";
import dtime from "moment";
import ACrypto from "@/utils/crypto";
import { cloneDeep } from "lodash-es";
import Sortable from "sortablejs";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useFind } from "./useFind";
import { ElDatePicker } from "element-plus";

// import MyTableFilterInput from "@/components/FilterInput/index.vue";
import type { VxeGridProps, VxeColumnPropTypes } from "vxe-table";
// import myVM from "./vm";

const { proxy } = useCurrentInstance();
const props = defineProps({
  name: {
    type: String,
    default: () => ""
  },
  father: {
    type: Object as PropType<object>,
    default: () => ({})
  },
  childs: {
    type: Object as PropType<object>,
    default: () => ({})
  },
  height: {
    type: String || Number,
    default: () => {
      return "auto";
    }
  },
  border: {
    type: Boolean,
    default: () => {
      return true;
    }
  },
  columns: {
    type: Array,
    default: () => {
      return [];
    }
  },
  childData: {
    type: Array as any,
    default: () => {
      return [];
    }
  },
  hasTableData: {
    // 只做判断使用
    type: Boolean,
    default: () => {
      return false;
    }
  },
  loading: {
    type: Boolean,
    default: () => {
      return false;
    }
  },
  paginationShow: {
    // 是否显示分页
    type: Boolean,
    default: () => {
      return false;
    }
  },
  tableMenu: {
    type: Object,
    default: () => {
      return {
        // enabled: true,
        // className: 'my-menus',
        // body: {
        //   options: [
        //     [
        //       { code: 'copy', name: '测试按钮', prefixIcon: 'fa fa-copy', className: 'my-copy-item' }
        //     ]
        //   ]
        // }
      };
    }
  },
  columnType: {
    type: String,
    default: () => {
      return "folder";
    }
  },
  fmtData: {
    type: Array,
    default: () => {
      return [];
    }
  },
  toolbarConfigVisible: {
    type: Boolean,
    default: false
  },
  tableSearch: {
    type: Boolean,
    default: false
  },
  searchSetting: {
    type: Boolean,
    default: false
  }
});

// const MyVM = new myVM(props.name, props.father, props.childs);

const emit = defineEmits([
  "refresh",
  "trigger",
  "rowClick",
  "rowdblClick",
  "selectChange",
  "pageChange",
  "viewFullText",
  "toSublevel",
  "pageNext",
  "pageAll",
  "menuClick",
  "showMetaData",
  "showFourAspectRecords",
  "fileDrop"
]);
const dynamicClass = reactive<any>({
  0: { class: "circle-bg0", name: "删除" },
  1: { class: "circle-bg1", name: "预归" },
  11: { class: "circle-bg11", name: "待审" },
  12: { class: "circle-bg12", name: "退回" },
  2: { class: "circle-bg2", name: "整理" },
  21: { class: "circle-bg21", name: "待存" },
  22: { class: "circle-bg22", name: "退整" },
  3: { class: "circle-bg3", name: "保存" }
});

// 文件拖拽相关状态
const isDragOver = ref(false);

// 文件拖拽事件处理函数
const handleDragOver = (e: DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
};

const handleDragEnter = (e: DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  isDragOver.value = true;
};

const handleDragLeave = (e: DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  // 只有当离开整个拖拽区域时才设置为false
  const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  const x = e.clientX;
  const y = e.clientY;
  if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
    isDragOver.value = false;
  }
};

const handleFileDrop = (e: DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  isDragOver.value = false;

  const files = e.dataTransfer?.files;
  if (files && files.length > 0) {
    // 将文件信息传递给父组件处理
    emit("fileDrop", {
      files: Array.from(files),
      columnType: props.columnType
    });
  }
};
const nextImgUrl = new URL("@/assets/images/next.png", import.meta.url).href;
const allImgUrl = new URL("@/assets/images/all.png", import.meta.url).href;
const globalStore = useGlobalStore();
const dynamicStore = useDynamicStore();
const dictionryStore = useDictionryStore();
const catalogStore = useCatalogStore();
const userStore = useUserStore();
// 系统色
const isDark = computed(() => (globalStore.isDark ? true : false));
if (isDark.value) {
  VxeUI.setTheme("dark");
} else {
  VxeUI.setTheme("light");
}
const size = computed<any>(() => globalStore.assemblySize); //尺寸
const gridTable = ref({} as VxeGridInstance); //表格实例
//vxt-table配置
// const tableColumns: any = ref([]); //表头
const tableLoading = ref(false);
// 点击时间间隔
const timer = ref();
// 操作列渲染防抖器
const columnTimer = ref<any>(null);

let sortable2: any;

const handleRefresh = () => {
  if (props.name === "tabbarRef") {
    emit("refresh");
  }
};
// 工具栏配置
const toolbarConfig = reactive({
  refresh: {
    icon: "vxe-icon-refresh",
    iconLoading: "vxe-icon-refresh roll",
    // queryMethod: handleRefresh
    queryMethod: () => emit("refresh")
  },
  import: {
    icon: "vxe-icon-cloud-upload"
  },
  export: {
    icon: "vxe-icon-cloud-download"
  },
  print: {
    icon: "vxe-icon-print"
  },
  zoom: {
    iconIn: "vxe-icon-fullscreen",
    iconOut: "vxe-icon-minimize"
  },
  custom: {
    icon: "vxe-icon-menu"
  },
  slots: {
    buttons: "toolbarButtons"
  }
});

// ****************** 搜索功能 ******************
// 弹框是否显示
const dialogVisible = ref(false);
const displayedData = ref<any>(); // 查找功能
const { searchContent, searchTable, searchNext, foundRows, currentIndex, highlightAndScrollToRow } = useFind(
  displayedData,
  gridTable
);
// ****************** 搜索功能 ******************

// 四性检测记录展示/抛出传递给父组件
const viewFourAspect = (row: any) => {
  console.log(row);
  emit("showFourAspectRecords", row);
};

// 表格事件
// 单击事件
const cellClick = ({ row, rowIndex, column }: { row: any; rowIndex: number; column: any }) => {
  clearTimeout(timer.value);
  timer.value = setTimeout(() => {
    // 筛除多选时单击触发操作
    if (!column.property) return;
    emit("rowClick", { row, rowIndex });
  }, 30);
};
// 双击事件
const cellDblclick = ({ row, rowIndex, column }: { row: any; rowIndex: number; column: any }) => {
  clearTimeout(timer.value);
  // 筛除多选时单击触发操作
  if (!column.property) return;
  emit("rowdblClick", { row, rowIndex });
};
// 勾选
const checkboxChange = (params: { records: any }) => {
  emit("selectChange", params.records);
};
// 全部勾选
const checkboxAll = (params: { records: any }) => {
  emit("selectChange", params.records);
};
// 快捷勾选
const checkboxRangeEnd = (params: { records: any }) => {
  emit("selectChange", params.records);
};
// 清除全部全选操作
const clearCheckboxRow = () => {
  gridTable.value.clearCurrentRow();
  gridTable.value.clearCheckboxRow();
};
// 多选操作勾选某行
const setCheckboxRow = (rows: any, checked: boolean) => {
  if (rows.length === 0) {
    // 清除全部多选选择
    clearCheckboxRow();
  } else {
    clearCheckboxRow();
    gridTable.value.setCheckboxRow(rows, checked);
  }
};
// 查看全文页面
const viewFullText = (row: any) => {
  emit("viewFullText", row);
};
// 跳转子页面
const toSublevel = (row: any, item?: any) => {
  emit("toSublevel", row, item);
};
// 右键事件
const rightMenuClick = ({ menu, row, column }: any) => {
  emit("menuClick", { menu, row, column });
};

// 局部加载页面数据
const reloadData = (data: any) => {
  displayedData.value = data;
};

// 类型定义
interface FmtDataItem {
  FMT_ID: string | number;
  FMT_ShowMetaData?: boolean;
  FMT_Name?: string;
}

interface TableRow {
  FMT_ID: string | number;
  Record_ID?: string | number;
  [key: string]: any;
}

// 检测数据中是否含有符合项
const checkFmtData = (arr: any[], fmtData: FmtDataItem[]): boolean => {
  if (!Array.isArray(arr) || !Array.isArray(fmtData)) return false;

  const fmtIdSet = new Set(fmtData.filter(v => v.FMT_ShowMetaData).map(v => v.FMT_ID));
  return arr.some(row => fmtIdSet.has(row.FMT_ID));
};

// 表格字段转换 - 优化性能和可读性
const formatter = ({ row, column, cellValue }: any): any => {
  const catalogList = catalogStore.catalogList;
  const ruleList =
    props.columnType === "folder"
      ? dynamicStore.visibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display")
      : dynamicStore.childVisibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display");

  const tempObj = ruleList.find((v: any) => v.FR_TableField === column.property);

  if (!tempObj) return cellValue;

  const [ruleType, param] = tempObj.FR_Rule.split(":");
  const ruleTypeLower = ruleType.toLowerCase();

  try {
    switch (true) {
      case tempObj.FR_Rule.includes("dictionary:"):
        return columnCoverter(tempObj.FR_Rule, cellValue);

      case ruleTypeLower.includes("datetime"):
        return row[tempObj.FR_TableField] ? dtime(row[tempObj.FR_TableField]).format(param) : cellValue;

      case ruleTypeLower.includes("userinfo"):
        const user = userStore.getUserList.find((v: any) => v.U_ID === cellValue);
        return user?.[param] || "";

      case ruleTypeLower.includes("catalogconvert"):
        const catalog = catalogList.find((v: any) => v.Catalog_ID === cellValue);
        return catalog?.[param] || "";

      case ruleTypeLower.includes("orgconvert"):
        const org = catalogList.find(v => v[tempObj.Field_Name] === cellValue);
        return org?.[param] || "";

      case ruleTypeLower.includes("jm"):
        return ACrypto.getSS(row[tempObj.FR_TableField]);

      case ruleTypeLower.includes("tozh"):
        return row[tempObj.FR_TableField] ? "是" : "否";

      default:
        return cellValue;
    }
  } catch (error) {
    console.warn("Formatter error:", error);
    return cellValue;
  }
};

// 标签字段转换函数
const labelFormatter = ({ row, column, cellValue }: any): any => {
  // 检查是否是标签字段
  if (column.property === "lables" || column.property === "Labels" || column.property === "labels") {
    if (!cellValue) return "";

    // 如果cellValue是字符串，按逗号分割
    let labelIds = [];
    if (typeof cellValue === "string") {
      labelIds = cellValue.split(",").filter(id => id.trim());
    } else if (Array.isArray(cellValue)) {
      labelIds = cellValue;
    } else {
      return cellValue;
    }

    // 从字典中获取标签名称
    if (dictionryStore.getDictionaryObj["labels"] && labelIds.length > 0) {
      const labelNames = labelIds.map(id => {
        const label = dictionryStore.getDictionaryObj["labels"].find((label: any) => label.DDL_ID === id.trim());
        return label ? label.DDL_Name : id.trim();
      });

      // 返回标签名称数组，供模板使用
      return labelNames;
    }
  }
  return cellValue;
};

// 下一页
const pageNext = () => {
  emit("pageNext");
};
// 全部
const pageAll = () => {
  emit("pageAll");
};
// 给表格加上自定义样式
const tableRowStyle = ({ row, rowIndex }: any) => {
  // 给每一行添加不可枚举属性rowIndex来标识当前行
  if (!Object.hasOwnProperty.call(row, "rowIndex")) {
    Object.defineProperty(row, "rowIndex", {
      value: rowIndex,
      writable: true,
      enumerable: false
    });
  }

  return row.MarkColor ? { background: row.MarkColor } : {};
};
let sortable1: any;

const rowDrop = (data: any[] = []) => {
  const $table = gridTable.value;
  sortable1 = Sortable.create($table.$el.querySelector(".body--wrapper>.vxe-table--body tbody"), {
    handle: ".vxe-body--column",
    onEnd: sortableEvent => {
      const newIndex = sortableEvent.newIndex as number;
      const oldIndex = sortableEvent.oldIndex as number;
      const currRow = dynamicStore.tableData.splice(oldIndex, 1)[0];
      dynamicStore.tableData.splice(newIndex, 0, currRow);
    }
  });
};
// 显示元数据弹框
const showMetaData = (row: any) => {
  emit("showMetaData", row);
};
// 列拖动
const columnDrop2 = () => {
  const $grid = gridTable.value;
  if (!$grid?.$el) return;

  const headerRow = $grid.$el.querySelector(".body--wrapper>.vxe-table--header .vxe-header--row");
  if (!headerRow) return;

  sortable2 = Sortable.create(headerRow, {
    handle: ".vxe-header--column",
    onEnd: sortableEvent => {
      const targetThElem = sortableEvent.item;
      const newIndex = sortableEvent.newIndex as number;
      const oldIndex = sortableEvent.oldIndex as number;
      const { fullColumn, tableColumn } = $grid.getTableColumn();
      const wrapperElem = targetThElem.parentNode as HTMLElement;
      const newColumn = fullColumn[newIndex];
      const oldColumn = fullColumn[oldIndex];

      // 检查是否为不允许移动的列
      const isInvalidMove = newColumn.fixed || oldColumn.fixed || newColumn.type === "checkbox" || oldColumn.type === "checkbox";

      if (isInvalidMove) {
        // 恢复原位置
        const oldThElem = wrapperElem.children[oldIndex] as HTMLElement;
        if (newIndex > oldIndex) {
          wrapperElem.insertBefore(targetThElem, oldThElem);
        } else {
          wrapperElem.insertBefore(targetThElem, oldThElem ? oldThElem.nextElementSibling : oldThElem);
        }

        const message = newColumn.fixed || oldColumn.fixed ? "固定列不允许拖动!" : "选择框不允许拖动!";
        proxy.$message.warning(message);
        return;
      }

      // 执行列移动
      try {
        const oldColumnIndex = $grid.getColumnIndex(tableColumn[oldIndex]);
        const newColumnIndex = $grid.getColumnIndex(tableColumn[newIndex]);
        const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
        fullColumn.splice(newColumnIndex, 0, currRow);
        $grid.loadColumn(fullColumn);
      } catch (error) {
        console.error("Column move error:", error);
        proxy.$message.error("列移动失败");
      }
    }
  });
};

// 计算操作列宽度（依赖所有相关 props）
const operationColumnWidth = computed(() => {
  const { childData, fmtData, columns } = props;
  const hasChildData = childData.length > 0;
  const hasValidFmtData = checkFmtData(columns, fmtData as FmtDataItem[]);
  if (hasChildData && hasValidFmtData) {
    return "290px";
  } else if (hasChildData || hasValidFmtData) {
    return "222px";
  } else {
    return "155px";
  }
});

const nameFilterRender = reactive<VxeColumnPropTypes.FilterRender>({
  name: "ElInput"
});
const date1FilterRender = reactive<VxeColumnPropTypes.FilterRender>({
  name: "ElDatePicker",
  props: {
    valueFormat: "YYYY-MM-DD"
  }
});
// 动态生成完整的列配置（计算属性）
const tableColumns = computed(() => {
  const cols = props.columns.map((item: any) => {
    if (customFields.includes(item.Field_Name)) {
      return {
        type: "html",
        field: item.Field_Name,
        title: item.DDM_CNName,
        width: item.DDM_DisplayWidth,
        align: "center",
        sortable: true,
        slots: { default: `${item.Field_Name}_default` }
      };
    } else {
      // 为Title字段添加筛选器的基础配置
      const baseConfig = {
        type: "html",
        field: item.Field_Name,
        title: item.DDM_CNName,
        width: item.DDM_DisplayWidth,
        sortable: true,
        formatter: formatter
      };
      // 如果是标签字段，使用标签转换器
      if (item.Field_Name === "lables" || item.Field_Name === "Labels" || item.Field_Name === "labels") {
        return {
          ...baseConfig,
          slots: { default: `${item.Field_Name}_default` }
        };
      }
      // 如果是Title字段，添加筛选器配置
      if (item.Field_Name === "Title") {
        return {
          ...baseConfig,
          filters: [{ data: "" }],
          filterRender: nameFilterRender,
          filterMethod({ option, row }: { option: any; row: any }) {
            console.log(ACrypto.getSS(row.Title).includes(option.data));
            return ACrypto.getSS(row.Title).includes(option.data);
          }
        };
      } else if (item.Field_Name === "Code") {
        return {
          ...baseConfig,
          filters: [{ data: "" }],
          filterRender: nameFilterRender,
          filterMethod({ option, row }: { option: any; row: any }) {
            return ACrypto.getSS(row.Code).includes(option.data);
          }
        };
      } else if (item.Field_Name === "Year") {
        // 提取Year字段值，去重，并转换为指定格式
        const uniqueYears = [...new Set(dynamicStore.tableData.map((v: any) => v.Year))]
          .filter(year => year !== null && year !== undefined && year !== "")
          .map(year => ({ label: String(year), value: String(year) }));

        return {
          ...baseConfig,
          filters: uniqueYears,
          filterMethod({ option, row }: { option: any; row: any }) {
            console.log(option, row, "option, row");

            return row.Year == option.value;
          }
          // filterRender: date1FilterRender
        };
      }
      return baseConfig;
    }
  });

  // 添加复选框列和操作列
  const operationCount = props.columnType === "folder" ? dynamicStore.tableData.length : undefined;

  return [
    { type: "checkbox", width: 55 },
    ...cols,
    {
      title: { text: props.columnType === "folder" ? "" : "操作", count: operationCount },
      width: operationColumnWidth.value,
      fixed: "right",
      slots: {
        default: "operation",
        header: "operation_title"
      }
    }
  ];
});
// 简化后的 watch（仅用于调试或必要操作）
watch(
  () => props.columns,
  newValue => {
    console.log("Columns updated:", newValue);
  },
  { deep: true, immediate: true }
);
watch(
  () => props.loading,
  (newVal, oldVal) => {
    tableLoading.value = newVal;
  },
  {
    immediate: true // 立即执行
  }
);
// 监听表格数据变化，触发tableColumns重新计算
watch(
  () => dynamicStore.tableData.length,
  () => {
    // tableColumns是计算属性，会自动重新计算，这里不需要手动赋值
    console.log("Table data length changed, tableColumns will auto-update");
  }
);
let initTime: any;
nextTick(() => {
  // 加载完成之后在绑定拖动事件
  initTime = setTimeout(() => {
    columnDrop2();
    // rowDrop();
  }, 500);
});

onUnmounted(() => {
  clearTimeout(initTime);
  if (sortable2) {
    sortable2.destroy();
    // sortable1.destroy();
  }
});

// 打开查找弹窗
const openSearchDialog = () => {
  dialogVisible.value = true;
};

// 打开查找弹窗
const closeSearchDialog = () => {
  if (foundRows.value.length > 0 && currentIndex.value >= 0) {
    highlightAndScrollToRow(foundRows.value[currentIndex.value], false);
  }
  searchContent.value = "";
  dialogVisible.value = false;
};
// 监听键盘事件
const handleKeydown = (event: { ctrlKey: any; key: string; preventDefault: () => void }) => {
  // 检查是否按下了 Enter 键
  if (event.key === "Enter") {
    openSearchDialog(); // 打开查找弹窗
  }
};
const name = ref(props.name);

// 滚动到指定Record_ID的行
const scrollToRowByRecordId = (recordId: string) => {
  if (!gridTable.value || !displayedData.value) return;

  const targetRow = displayedData.value.find((row: any) => row.Record_ID === recordId);
  if (targetRow) {
    gridTable.value.scrollToRow(targetRow);
    gridTable.value.setCurrentRow(targetRow);
  }
};

defineExpose({ setCheckboxRow, reloadData, cellClick, name, scrollToRowByRecordId });
</script>

<style>
.vxe-table--fixed-right-wrapper .vxe-header--column .vxe-cell {
  position: relative;
  height: 100%;
}
</style>
<style lang="scss">
@import "@/styles/vxe-table.scss";
.highlight {
  background-color: yellow;
}
.circle {
  display: inline-block;
  width: 28px;
  height: 18px;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  border-radius: 2px;
}
.circle-bg1 {
  color: #ffffff;
  background: rgb(218 143 143);
  box-shadow: 0 0 3px var(--el-color-primary);
}
.circle-bg3 {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-6);
  box-shadow: 0 0 3px var(--el-color-primary);
}
.circle-bg12,
.circle-bg22 {
  color: #ffffff;
  background: red;
  box-shadow: 0 0 3px var(--el-color-primary);
}
.circle-bg11 {
  color: #ffffff;
  background: rgb(224 17 200);
  box-shadow: 0 0 3px var(--el-color-primary);
}
.circle-bg2 {
  color: #ffffff;
  background: rgb(161 45 111);
  box-shadow: 0 0 3px var(--el-color-primary);
}
.circle-bg21 {
  color: #ffffff;
  background: rgb(54 102 124);
  box-shadow: 0 0 3px var(--el-color-primary);
}
.table-page {
  position: relative;
  height: 100%;
  transition: all 0.3s ease;
  &.drag-over {
    background-color: rgb(64 158 255 / 10%);
    border: 2px dashed var(--el-color-primary);
  }
  .drag-hint {
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 1000;
    padding: 20px;
    text-align: center;
    background-color: rgb(255 255 255 / 95%);
    border: 2px dashed var(--el-color-primary);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
    transform: translate(-50%, -50%);
    .el-icon {
      margin-bottom: 10px;
      color: var(--el-color-primary);
    }
    p {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
      color: var(--el-color-primary);
    }
  }
  .loadImg {
    position: absolute;

    // top: 36px;
    right: 15px;
    bottom: 0;
    z-index: 999;
    display: flex;
    flex-direction: column;
    height: 50%;
    margin: auto;
  }
  .ant-spin-nested-loading {
    margin: 0;
  }
  .vxe-grid--table-container {
    position: relative;
    .optionsColumn {
      .el-button {
        position: absolute;
        top: 50%;
        right: 4px;
        transform: translateY(-50%);
      }
    }
  }
}

// .columOptions {
//   width: 270px;
// }
</style>
